package com.effectiv.gooruda.rest.service.impl;

import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import org.springframework.stereotype.Component;

import com.effectiv.gooruda.rest.domain.Permission;

import com.effectiv.gooruda.rest.ext.ExtResponse;
import com.effectiv.gooruda.rest.service.api.PermissionService;

//Error code - 271-280

@Component
public class PermissionServiceImpl extends PermissionService {

	public Response create(Permission p) {
		Permission permission = findByNameInternal(p.getName());

		if (permission != null) {

			throwException(271, "Permission with name " + p.getName()
					+ " already exists.");
		}

		getTemplate().save(p, getCollection());

		ExtResponse res = new ExtResponse();
		res.setId(permission.getId());
		res.setMessage("Permission added successfully.");

		GenericEntity<ExtResponse> entity = new GenericEntity<ExtResponse>(res,
				ExtResponse.class);

		ResponseBuilder builder = Response.ok(entity);

		return builder.build();

	}

	public Permission findByNameInternal(String p) {

		Query query = new Query();
		query.addCriteria(Criteria.where("name").is(p));

		Permission permission = getTemplate().findOne(query, Permission.class,
				getCollection());

		return permission;
	}

	public Response findByName(String p) {

		Query query = new Query();
		query.addCriteria(Criteria.where("name").is(p));

		Permission permission = getTemplate().findOne(query, Permission.class,
				getCollection());

		ExtResponse res = new ExtResponse();

		if (permission == null) {
			res.setMessage("Permission not found for name - " + p);
		} else {
			res.setMessage("Permission found.");
			res.setValue(permission);
		}

		GenericEntity<ExtResponse> entity = new GenericEntity<ExtResponse>(res,
				ExtResponse.class);

		ResponseBuilder builder = Response.ok(entity);

		return builder.build();
	}

	public Response findOne(String id) {

		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id));

		Permission permission = getTemplate().findOne(query, Permission.class,
				getCollection());

		ExtResponse res = new ExtResponse();

		if (permission == null) {
			res.setMessage("Permission not found for id - " + id);
		} else {
			res.setMessage("Permission found.");
			res.setValue(permission);
		}

		GenericEntity<ExtResponse> entity = new GenericEntity<ExtResponse>(res,
				ExtResponse.class);

		ResponseBuilder builder = Response.ok(entity);

		return builder.build();
	}

}
